/*
 * Copyright (c) 2002-2006 Universidade Federal de Campina Grande This program
 * is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version. This
 * program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package org.ourgrid.worker.collectors.gmond;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import org.w3c.dom.NodeList;

public class GMondUtilsLinux extends GMondUtils {
	
	public boolean isGMondInstalled() {
		File gmondExecutableFile = new File("/usr/sbin/gmond");
		return gmondExecutableFile.exists();
	}
	
	protected void startGMondDaemon() throws IOException {
		String command = "/usr/sbin/gmond";
		Runtime.getRuntime().exec(command);
	}
	
	public void stopGMond() throws IOException {
		String command = "/usr/bin/killall gmond";
		Runtime.getRuntime().exec(command);
	}
	
	public boolean isGMondRunning() throws IOException {
		Process process = Runtime.getRuntime().exec("/bin/ps -A");
		Scanner sc = new Scanner(process.getInputStream());
		
		while(sc.hasNextLine()) {
			String line = sc.nextLine();
			if(line.indexOf("gmond") >= 0){
				return true;
			}
		}

		return false;
	}
	
	public int getGmondPort(String configFile) throws GMondCollectorException {
		Scanner sc;
		try {
			sc = new Scanner(new BufferedReader(new FileReader(configFile)));
		} catch (FileNotFoundException e) {
			throw new GMondCollectorException("Could not find gmond configuration file.");
		}
		while(sc.hasNext()) {
			if( sc.next().startsWith("tcp_accept_channel") ) {
				while(! sc.next().equals("port") ) {}
				sc.next(); // equals simbol
				return Integer.parseInt(sc.next());
			}
		}
		
		return -1;
	}
	
	public String getGmondAddress() {
		return "127.0.0.1";
	}

	@Override
	public String getGmondConfigFile() {
		return "/etc/ganglia/gmond.conf";
	}

}
